package com.dcivision.dms.core;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import uk.ltd.getahead.dwr.ExecutionContext;

import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;

/**
 * SystemUpdater.java 
 * This class will call by dwr(js) method to do some special action.
 * @author          Lee Lv
 * @company         DCIVision Limited
 * @creation date   11/11/2006
 * @version         $Revision: 1.2 $
*/
public class SystemUpdater {
  
  public static final String REVISION = "$Revision: 1.2 $";
  
  private Log log = new LogFactoryImpl().getInstance(this.getClass());
  
  public static String LUCENE_UPDATE_MESSAGE_UPDATE_COUNTER = "session.message.lucene.update.counter";
  
  public static String LUCENE_UPDATE_MESSAGE_UPDATE_RECORDCOUNT = "session.message.lucene.update.recordcount";
  
  public static String DMS_SYSTEM_CHECKER_COUNTER = "session.message.dms.check.counter";
  
  public static String DMS_SYSTEM_CHECKER_RECORDCOUNT = "session.message.dms.check.recordcount";
  
  public static String DMS_SYSTEM_CHECKER_MESSAGE = "session.message.dms.check.message";
  
  public SystemUpdater() {
    super();
  }
  
  /**
   * Update or reindex lucene data.
   * @param backupPath
   * @param updateOldLucene
   * @return
   * @throws Exception
   */
  public String startRunUpdater(String backupPath, String updateOldLucene) throws Exception {
    HttpServletRequest request = ExecutionContext.get().getHttpServletRequest();
    
    SessionContainer sessionContainer = null;
    Connection conn = null;
    try {
      request.getSession().setAttribute(SystemUpdater.LUCENE_UPDATE_MESSAGE_UPDATE_COUNTER, "0");
      request.getSession().setAttribute(SystemUpdater.LUCENE_UPDATE_MESSAGE_UPDATE_RECORDCOUNT, "0");
      
      sessionContainer = this.getSessionContainer(request);
      conn = this.getDBConnection();
      
      //start lucene update
      if (backupPath!=null && updateOldLucene!=null) {
        boolean isUpdateOld = "true".equals(updateOldLucene);
        LuceneUpdater luceneUpdater = new LuceneUpdater(sessionContainer, conn);
        String message = luceneUpdater.startUpdate(request, backupPath, isUpdateOld);
        return message;
      }else {
        return "ERROR: backup path is empty.";
      }
    }catch (Exception ex) {
      log.error(ex, ex);
      throw ex;
    }finally {
      request.getSession().removeAttribute(LUCENE_UPDATE_MESSAGE_UPDATE_COUNTER);
      request.getSession().removeAttribute(LUCENE_UPDATE_MESSAGE_UPDATE_RECORDCOUNT);
      sessionContainer = null;
      try {conn.close();}catch(Exception ex) {} finally {conn = null;}
    }
  }
  
  /**
   * Get lucene update message for process bar.
   * @return
   */
  public String getLuceneUpdateMessage() {
    HttpServletRequest request = ExecutionContext.get().getHttpServletRequest();
    try {
      int counter = Integer.parseInt((String)request.getSession().getAttribute(LUCENE_UPDATE_MESSAGE_UPDATE_COUNTER));
      int recordCount = Integer.parseInt((String)request.getSession().getAttribute(LUCENE_UPDATE_MESSAGE_UPDATE_RECORDCOUNT));
      return counter+"/"+recordCount;
    }catch (Exception ex) {
      return 0+"/"+0;
    }
  }
  
  /**
   * Start dms checking
   * @return
   * @throws Exception
   */
  public String startRunChecker() throws Exception {
    HttpServletRequest request = ExecutionContext.get().getHttpServletRequest();
    
    SessionContainer sessionContainer = null;
    Connection conn = null;
    try {
      request.getSession().setAttribute(DMS_SYSTEM_CHECKER_COUNTER, "0");
      request.getSession().setAttribute(DMS_SYSTEM_CHECKER_RECORDCOUNT, "0");
      
      sessionContainer = this.getSessionContainer(request);
      conn = this.getDBConnection();
      
      //start lucene update
      DmsChecker dmsChecker = new DmsChecker(sessionContainer, conn);
      dmsChecker.startCheck(request);
      
      return dmsChecker.getResultSummary();
    }catch (Exception ex) {
      log.error(ex, ex);
      throw ex;
    }finally {
      request.getSession().removeAttribute(DMS_SYSTEM_CHECKER_COUNTER);
      request.getSession().removeAttribute(DMS_SYSTEM_CHECKER_RECORDCOUNT);
      sessionContainer = null;
      try {conn.close();}catch(Exception ex) {} finally {conn = null;}
    }
  }
  
  /**
   * Get dms checking message for process bar.
   * @return
   */
  public String getDmsCheckMessage() {
    HttpServletRequest request = ExecutionContext.get().getHttpServletRequest();
    try {
      int counter = Integer.parseInt((String)request.getSession().getAttribute(DMS_SYSTEM_CHECKER_COUNTER));
      int recordCount = Integer.parseInt((String)request.getSession().getAttribute(DMS_SYSTEM_CHECKER_RECORDCOUNT));
      return counter+"/"+recordCount;
    }catch (Exception ex) {
      return 0+"/"+0;
    }
  }
  
  private SessionContainer getSessionContainer(HttpServletRequest request) {
    SessionContainer ctx = (SessionContainer)request.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    if (ctx==null) {
      ctx = new SessionContainer();
      request.getSession().setAttribute(GlobalConstant.SESSION_CONTAINER_KEY, ctx);
    }
    return(ctx);
  }
  
  //get Connection Object.
  private Connection getDBConnection(){
    Connection conn = null;
    try{
      conn = DataSourceFactory.getConnection();
    }catch(Exception e){
      log.error("get Connection error!");
    }
    return conn;
  }
}
